import React, { useEffect, useRef, useState } from "react";
import { Card, Avatar, List, Input, Button, Space, Tag, Dropdown, Menu, message as antdMsg } from "antd";
import type { ConsultMessage, ConsultSession, QuickReply } from "../../types/consult";
import { useParams } from "react-router-dom";
import Layout from "../../components/Layout";

const mockPatient = { id: "p1", name: "张三", type: "patient" };
const mockSession: ConsultSession = {
  id: "s1",
  patient: mockPatient,
  doctor: { id: "doc1", name: "王医生", type: "doctor" },
  status: '进行中',
  lastMessage: null,
  messages: [
    { id: 'm1', sessionId: 's1', senderId: 'p1', senderType: 'patient', type: 'text', content: '医生您好', sendTime: '2024-06-07 09:00' },
    { id: 'm2', sessionId: 's1', senderId: 'doc1', senderType: 'doctor', type: 'text', content: '您好，请问哪里不舒服？', sendTime: '2024-06-07 09:01' }
  ],
  createdAt: '2024-06-07 09:00',
  updatedAt: '2024-06-07 09:10',
};
const quickReplies: QuickReply[] = [
  { id: 'q1', content: '您好，请具体描述您的症状。' },
  { id: 'q2', content: '请上传病历图片，谢谢。' },
  { id: 'q3', content: '如不方便来院，可预约线上视频门诊。' },
];

const ConsultChat: React.FC = () => {
  const { id } = useParams();
  const [messages, setMessages] = useState<ConsultMessage[]>(mockSession.messages);
  const [input, setInput] = useState('');
  const [status, setStatus] = useState<'进行中'|'已结束'>(mockSession.status);
  const msgEndRef = useRef<HTMLDivElement>(null);
  // 发送消息（模拟WebSocket）
  const send = (msg: Partial<ConsultMessage>) => {
    setTimeout(() => {
      setMessages(msgs => [...msgs, {
        id: Date.now()+Math.random()+'',
        sessionId: mockSession.id,
        senderId: 'doc1',
        senderType: 'doctor',
        type: msg.type||'text',
        content: msg.content||'',
        sendTime: new Date().toLocaleString()
      }]);
    }, 400);
  };
  useEffect(() => { msgEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [messages]);
  // 状态变化
  const closeChat = () => {
    setStatus('已结束');
    antdMsg.success('本次咨询已结束');
  };
  return (
    <Layout title="在线咨询">
      <Card
        style={{ maxWidth: 700, margin: '0 auto' }}
        title={<Space><Avatar>{mockPatient.name[0]}</Avatar><span>{mockPatient.name}</span><Tag color={status==="进行中"?'green':'default'}>{status}</Tag></Space>}
        bodyStyle={{ padding: 12, minHeight: 360 }}
        extra={status==='进行中' && <Button danger size="small" onClick={closeChat}>结束咨询</Button>}
      >
      <List
        dataSource={messages}
        renderItem={m => (
          <List.Item style={{ justifyContent: m.senderType==='doctor'? 'flex-end':'flex-start', border: 'none' }}>
            <Space direction={m.senderType==='doctor'?'rtl':'ltr'}>
              <Avatar>{m.senderType==='patient'?mockPatient.name[0]:'医生'}</Avatar>
              {m.type==='text'?
                <span style={{ background: '#f4faff', borderRadius: 8, padding: '8px 12px', maxWidth: 260, display: 'inline-block' }}>{m.content}</span>
                :
                <img src={m.content} alt="pic" style={{ maxWidth: 100, borderRadius: 6, border: '1px solid #eee' }} />
              }
            </Space>
          </List.Item>
        )}
      />
      <div ref={msgEndRef} />
      {status==='进行中' && (
        <Space style={{width:'100%',marginTop:16}} align="start">
          <Input.TextArea value={input} onChange={e=>setInput(e.target.value)} autoSize={{minRows:1,maxRows:3}} style={{flex:1}} placeholder="输入消息"/>
          <Dropdown
            overlay={<Menu>
              {quickReplies.map(q => <Menu.Item key={q.id} onClick={()=>send({type: 'text', content: q.content})}>{q.content}</Menu.Item>)}
            </Menu>}
            placement="topRight"
          >
            <Button>快捷回复</Button>
          </Dropdown>
          <Button type="primary" onClick={()=>{ send({ type:'text', content:input }); setInput(''); }} disabled={!input.trim()}>发送</Button>
        </Space>
      )}
      </Card>
    </Layout>
  );
};
export default ConsultChat;
